import { exec } from 'child_process'
import { promisify } from 'util'
import net from 'net'
import * as fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const execAsync = promisify(exec)

// 需要检查的端口
const PORTS_TO_CHECK = [3000, 5173, 5174, 5175]
const LOCK_FILE_DIR = path.join(__dirname, '../.locks')
const MAX_WAIT_TIME = 10000 // 10 seconds

// 创建锁文件目录
try {
  if (!fs.existsSync(LOCK_FILE_DIR)) {
    fs.mkdirSync(LOCK_FILE_DIR, { recursive: true })
  }
} catch (error) {
  console.error('Error creating lock directory:', error)
  process.exit(1)
}

// 清理所有锁文件
function cleanLockFiles() {
  try {
    if (fs.existsSync(LOCK_FILE_DIR)) {
      const files = fs.readdirSync(LOCK_FILE_DIR)
      for (const file of files) {
        fs.unlinkSync(path.join(LOCK_FILE_DIR, file))
      }
    }
  } catch (error) {
    console.error('Error cleaning lock files:', error)
  }
}

// 检查端口是否被占用
function isPortInUse(port) {
  return new Promise((resolve) => {
    const server = net.createServer()
    server.once('error', (err) => {
      if (err.code === 'EADDRINUSE') {
        resolve(true)
      }
    })
    server.once('listening', () => {
      server.close()
      resolve(false)
    })
    server.listen(port)
  })
}

// 获取占用端口的进程 PID
async function getProcessOnPort(port) {
  try {
    const { stdout } = await execAsync(`lsof -i :${port} -t`)
    return stdout.trim().split('\n').filter(Boolean)
  } catch (error) {
    return []
  }
}

// 强制结束占用端口的进程
async function killPortProcess(port) {
  try {
    // 查找并强制终止所有占用该端口的进程
    await execAsync(`lsof -i :${port} | grep LISTEN | awk '{print $2}' | xargs kill -9`)
    console.log(`Successfully killed processes on port ${port}`)
    return true
  } catch (error) {
    // 如果没有找到进程或已经被终止，则认为是成功的
    if (error.message.includes('No such process')) {
      return true
    }
    console.error(`Error killing processes on port ${port}:`, error.message)
    return false
  }
}

// 主函数
async function killAllPortProcesses() {
  console.log('Checking and killing processes on required ports...')
  
  for (const port of PORTS_TO_CHECK) {
    try {
      await killPortProcess(port)
    } catch (error) {
      console.error(`Failed to handle port ${port}:`, error)
    }
    // 添加短暂延迟确保端口释放
    await new Promise(resolve => setTimeout(resolve, 500))
  }
}

// 清理函数
function cleanup() {
  console.log('Cleaning up...')
  cleanLockFiles()
}

// 注册清理函数
process.on('exit', cleanup)
process.on('SIGINT', () => {
  cleanup()
  process.exit()
})
process.on('SIGTERM', () => {
  cleanup()
  process.exit()
})
process.on('uncaughtException', (error) => {
  console.error('Uncaught exception:', error)
  cleanup()
  process.exit(1)
})

// 运行清理
console.log('Starting port cleanup...')
killAllPortProcesses()
  .then(() => {
    console.log('Port cleanup completed')
    process.exit(0)
  })
  .catch((error) => {
    console.error('Port cleanup failed:', error)
    process.exit(1)
  }) 